from .models import Node
import json


class node_tree(object):
    '''
    根据queryset
    '''
    @staticmethod
    def digui(row):
        for c in Node.objects.filter(parent_node=row.id):
            c.children = []
            row.children.append(c)
            node_tree.digui(c)

    @staticmethod
    def create_tree(node_list):
        ret = []
        for row in node_list:
            row.children = []
            ret.append(row)
            node_tree.digui(row)
        return ret


def node_tree_list(data):
    '''
    根据objects.values
    生成符合layui格式的数据源
    :data:  Node.objects.values()
    :return:
    '''
    node_list = list(data)
    node_dic = {}
    node_tree_list = []
    for n in node_list:
        n['children'] = []
        n['title'] = n['name']
        node_dic[n['id']] = n
        n['checkArr'] = '0'
        n['basicData'] = {'type': n['node_type']} #n['node_type']
        n['parentId'] = n['parent_node_id']
    for n in node_list:
        if n['parent_node_id']:
            node_dic[n['parent_node_id']]['children'].append(node_dic[n['id']])
        else:
            node_tree_list.append(node_dic[n['id']])
    node_tree_json = json.dumps(node_tree_list)

    return node_tree_json



def node_order_tree(node_list, node_queryset):
    '''
    按照第一个顶级栏目子栏目第二个顶级栏目子栏目...这样排序, 如果要排序所有栏目nodeid传0
    :param node_list: 返回的栏目列表
    :return:
    '''

    for node in node_queryset:
        node_list.append(node)
        s_node_set = Node.objects.filter(parent_node_id=node.id)
        node_order_tree(node_list, s_node_set)
    return node_list



###begin
def article_node_order_tree(n_list, top_list, node_list):
    '''
    按照第一个顶级栏目子栏目第二个顶级栏目子栏目...这样排序, 显示文章的栏目结构
    :param n_list: 返回的栏目列表
    :return:
    '''
    for id in top_list:
        node = Node.objects.get(id=id)
        n_list.append(node)
        s_node_set = Node.objects.filter(parent_node_id=node.id, id__in=node_list, is_active=True)
        s_node_list = [x.id for x in s_node_set]

        article_node_order_tree(n_list, s_node_list, node_list)

    return n_list

def GetNodeTree():
    node_queryset = Node.objects.filter(node_type='content')
    node_list = []
    top_list = []
    for n in node_queryset:
        if n.node_level == 1:
            top_list.append(n.id)
        else:
            node_list.append(n.id)
            i = 0
            for nn in n.node_path.split(','):
                if i == 0:
                    top_list.append(int(nn))
                else:
                    node_list.append(int(nn))
                i = i + 1

    top_list = set(top_list)
    node_list = set(node_list)
    node_trees = article_node_order_tree([], top_list, node_list)

    return node_trees
###end


